//
//  ListenTestViewController.m
//  Learn
//
//  Created by 迟建国 on 2024/4/2.
//  Copyright © 2024 迟建国. All rights reserved.
//

#import "ListenTestViewController.h"
#import "TestOptionTableViewCell.h"
#import "SubmitListenTestViewController.h"
#import "TextbookChapterDetailModel.h"
#import "HomeRequest.h"
#import "TextbookChapterDetailModel.h"
#import "TingshuoTestCollectionViewCell.h"
#import "RecordHelper.h"
#import "CircleProgressView.h"
#import "TestSelectedQuestionView.h"

@interface ListenTestViewController ()<UICollectionViewDelegate, UICollectionViewDataSource,IFlyDetectionDelegate,PlayManagerDelegate,PlayManagerDelegate>
@property (nonatomic, strong) UICollectionView *collectionView;
@property (nonatomic, strong) TextbookQuestionsModel *testModel;
@property (nonatomic, assign) NSInteger currentIndex;
@property (nonatomic,strong) IFlyDetection *detection;//评测对象
@property (nonatomic,strong) RecordHelper *recordHelper;

@property (nonatomic, strong) UILabel *timeL;
@property (nonatomic, strong) UIView *bottomView;
@property (nonatomic, strong) CircleProgressView *progressView;
@property (nonatomic, strong) TestSelectedQuestionView *alertView;

@property (nonatomic, strong) UIImageView *statuesImg;

@property (nonatomic, strong) UIButton *alertBtn;

@property (nonatomic, strong) UIButton *nextBtn;

@property (nonatomic, strong) NSDictionary *data;

@property (nonatomic, assign) BOOL isReDo;//是否重做

@end

@implementation ListenTestViewController
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:YES];
    
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *fileName = [NSString stringWithFormat:@"%@",lApp.useModel.username];
    NSString *path = [[paths objectAtIndex:0] stringByAppendingPathComponent:fileName];
    
    [[NSFileManager defaultManager] createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:nil];
}
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:YES];
    [[PlayManager sharPlayManager] pause];
    [self.detection stop];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = self.model.resourceName;
    self.view.backgroundColor = rgba(245, 245, 245, 1);
    [PlayManager sharPlayManager].useTime = 0;
    
    [MethodTool checkMicrophonePromiss:self];
    
    self.detection.delegate = self;
    [self.detection evalutType:0];
    [self.detection evalutSource:1];
    [self.detection evalutLanguage:1];
    
    self.currentIndex = 0;
    [self setUI];
    [self setNavUI];
    [self loadData];
    
    //    self.s = [[IFlySynthesis alloc] init];
    // Do any additional setup after loading the view.
}
- (void)loadData {
    NSString *type = @"";
    if (self.type == BookTypeHearsay) {
        type = @"听说";
        self.alertBtn.hidden =  YES;
    } else if (self.type == BookTypeHearing) {
        type = @"听力";
    } else if (self.type == BookTypeFollowUpReading) {
        type = @"跟读";
    } else if (self.type == BookTypeWrittenExam) {
        type = @"笔试";
    } else if (self.type == BookTypePhonetic) {
        type = @"音标";
    } else if (self.type == BookTypeModelsp) {
        type = @"典范";
    } else if (self.type == BookTypeNewconcept) {
        type = @"新概念";
    } else if (self.type == BookTypeBlackplum) {
        type = @"黑布林";
    } else if (self.type == BookTypeInterest) {
        type = @"趣味";
    }  else {
        
    }
    WeakSelf(self);
    [HomeRequest getTextbookTestQuestionsWithId:self.model.versionId type:type result:^(TextbookQuestionsModel *model) {
        weakself.testModel = model;
        [weakself dealData];
        [weakself.collectionView reloadData];
        if (weakself.type == BookTypeHearsay) {
            weakself.alertView.titleArray = weakself.testModel.resource.items;
            weakself.alertBtn.hidden =  weakself.testModel.resource.items.count == 0;
        }
        
    }];
}

- (void)setUI {
    UIView *testView = [[UIView alloc] init];
    testView.backgroundColor = [UIColor whiteColor];
    testView.layer.cornerRadius = 15;
    testView.layer.masksToBounds = YES;
    [self.view addSubview:testView];
    [testView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view.mas_left).offset(10);
        make.top.equalTo(self.view.mas_top).offset(10 + lTopBarHeight);
        make.right.equalTo(self.view.mas_right).offset(-10);
        make.bottom.equalTo(self.view.mas_bottom).offset(-SafeAreaBottomHeight - 116);
    }];
    
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    layout.minimumInteritemSpacing = 0; // 水平间距
    layout.minimumLineSpacing = 0; // 垂直间距
    layout.sectionInset = UIEdgeInsetsMake(0, 0, 0, 0); // 边界间距
    layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    UICollectionView *collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0,0, SCREEN_W - 20, SCREEN_H - lTopBarHeight - SafeAreaBottomHeight - 126) collectionViewLayout:layout];
    collectionView.backgroundColor = [UIColor whiteColor];
    collectionView.delegate = self;
    collectionView.dataSource = self;
    [testView addSubview:collectionView];
    self.collectionView = collectionView;
    collectionView.showsVerticalScrollIndicator = NO;
    collectionView.showsHorizontalScrollIndicator = NO;
    collectionView.alwaysBounceVertical = NO;
    collectionView.scrollEnabled = NO;
    self.extendedLayoutIncludesOpaqueBars = YES;
    
    [collectionView registerNib:[UINib nibWithNibName:@"TingshuoTestCollectionViewCell" bundle:[NSBundle mainBundle]] forCellWithReuseIdentifier:@"TingshuoTestCollectionViewCell"];
    
   
    CircleProgressView *view = [[CircleProgressView alloc] init];
    view.frame = CGRectMake(0, 0, 72, 72);
    view.progressColor = rgba(12, 183, 108, 1);
    view.trackColor = rgba(224, 224, 224, 1);
    view.hidden = YES;
    view.progress = 0;
    view.startPoint = 90;
    view.lineWidth = 2.5;
    
    [self.view addSubview:view];
    self.progressView = view;
    
   
    self.statuesImg = [UIImageView new];
    [self.view addSubview: self.statuesImg];
    [view mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(testView.mas_bottom).offset(6);
        make.centerX.equalTo(testView.mas_centerX);
        make.width.height.mas_equalTo(72);
    }];
    [self.statuesImg mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(testView.mas_bottom).offset(16);
        make.centerX.equalTo(testView.mas_centerX);
        make.width.height.mas_equalTo(52);
    }];
    
    
    self.nextBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.nextBtn setTitle:@"下一步" forState:UIControlStateNormal];
    [self.nextBtn setTitleColor:rgba(12, 183, 108, 1) forState:UIControlStateNormal];
    self.nextBtn.titleLabel.font = [UIFont fontWithName:@"PingFangSC-Semibold" size:16];
    [self.view addSubview:self.nextBtn];
    [self.nextBtn addTarget:self action:@selector(clickToNext) forControlEvents:UIControlEventTouchUpInside];
    [self.nextBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.view.mas_right).offset(-56);
        make.centerY.equalTo(self.statuesImg.mas_centerY);
        make.height.offset(44);
    }];
    
    UIView *bottomView = [[UIView alloc] initWithFrame:CGRectMake(0, SCREEN_H - SafeAreaBottomHeight - 28, SCREEN_W, 28)];
    bottomView.backgroundColor = rgba(12, 183, 108, 0.1);
    bottomView.hidden = YES;
    [self.view addSubview:bottomView];
    self.bottomView = bottomView;
    UILabel *timeL = [[UILabel alloc] init];
    timeL.text = @"准备时间 剩余0s";
    timeL.font = [UIFont fontWithName:@"PingFangSC-Semibold" size:12];
    timeL.textColor = rgba(51, 51, 51, 1);
    [bottomView addSubview:timeL];
    self.timeL = timeL;
    [timeL mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(bottomView.mas_centerX);
        make.centerY.equalTo(bottomView.mas_centerY);
    }];
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.testModel.resource.items.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    TingshuoTestCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"TingshuoTestCollectionViewCell" forIndexPath:indexPath];
    if (!cell) {
        cell = [[[NSBundle mainBundle]loadNibNamed:@"TingshuoTestCollectionViewCell" owner:self options:nil] lastObject];
    }
    
    cell.resmain = self.testModel.resmain;
    cell.progressView = self.progressView;
    cell.timeL = self.timeL;
    cell.bottomView = self.bottomView;
    cell.statuesImg = self.statuesImg;
    cell.detection = self.detection;
    cell.nextBtn = self.nextBtn;
    
    WeakSelf(self);
    cell.readFinishBlock = ^(HSItem * _Nonnull model) {
        [weakself nextModel];
    };
    
    cell.model = self.testModel.resource.items[indexPath.row];
    cell.modelAnswer = self.testModel.resource_h5.parts[indexPath.row];
    if (self.currentIndex == indexPath.row) {
        [cell startTest];
    }
    
    return cell;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    return CGSizeMake(SCREEN_W - 20, SCREEN_H - NavigationBarHeight - SafeAreaBottomHeight - 126);
}
- (void)nextModel
{
    if (self.isReDo) {
        [self goSubmitVC];
        return;
    }
    
    if (self.currentIndex == self.testModel.resource.items.count - 1) {
        
        [self goSubmitVC];
        return;
    }
    self.currentIndex ++;
    NSIndexPath *indexPath = [NSIndexPath indexPathForItem:self.currentIndex inSection:0]; // 滚动到第一个 section 的第一个 item
    [self.collectionView scrollToItemAtIndexPath:indexPath
                                atScrollPosition:UICollectionViewScrollPositionCenteredHorizontally
                                        animated:YES];
    [self.collectionView reloadData];
    
}
- (void)goSubmitVC
{
    self.isReDo = NO;
    NSIndexPath *indexPath = [NSIndexPath indexPathForItem:self.currentIndex inSection:0];
    TingshuoTestCollectionViewCell *cell = [self.collectionView cellForItemAtIndexPath:indexPath];
    [cell stop];
    SubmitListenTestViewController *vc = [[SubmitListenTestViewController alloc] init];
    vc.model = self.testModel;
    vc.title = self.model.resourceName;
    vc.mission_id = self.mission_id;
    vc.blcok = ^(NSInteger index) {
        self.isReDo = YES;
        self.currentIndex = index;
        NSIndexPath *indexPath = [NSIndexPath indexPathForItem:self.currentIndex inSection:0];
        [self.collectionView scrollToItemAtIndexPath:indexPath
                                        atScrollPosition:UICollectionViewScrollPositionCenteredHorizontally
                                                animated:YES];
        [self.collectionView reloadData];
        
    };
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)setNavUI {
    UIView *nav = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_W, NavigationBarHeight)];
    nav.backgroundColor = rgba(245, 245, 245, 1);
    [self.view addSubview:nav];
    //    self.nav = nav;
    
    UIButton *backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [backBtn setImage:[UIImage imageNamed:@"icon_back"] forState:UIControlStateNormal];
    [backBtn addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside];
    [nav addSubview:backBtn];
    [backBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(nav.mas_left).offset(5);
        make.bottom.equalTo(nav.mas_bottom);
        make.width.offset(50);
        make.height.offset(44);
    }];
    
    UILabel *titleL = [[UILabel alloc] init];
    titleL.text = self.model.resourceName;
    titleL.font = [UIFont fontWithName:@"PingFangSC-Semibold" size:16];
    titleL.textColor = rgb(51, 51, 51);
    titleL.textAlignment = NSTextAlignmentCenter;
    [nav addSubview:titleL];
    [titleL mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(nav.mas_bottom);
        make.centerX.equalTo(nav.mas_centerX);
        make.height.offset(44);
    }];
    
    
    UIButton *saveBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [saveBtn setImage:[UIImage imageNamed:@"icon_save"] forState:UIControlStateNormal];
    
    self.alertBtn = saveBtn;
    [saveBtn addTarget:self action:@selector(save) forControlEvents:UIControlEventTouchUpInside];
    [nav addSubview:saveBtn];
    [saveBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.view.mas_right).offset(-10);
        make.bottom.equalTo(nav.mas_bottom);
        make.height.offset(44);
    }];
    
}

- (void)save {
    
    [self.alertView showView];
    
}
- (void)back {
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)clickToNext
{
    NSIndexPath *indexPath = [NSIndexPath indexPathForItem:self.currentIndex inSection:0];
    TingshuoTestCollectionViewCell *cell = [self.collectionView cellForItemAtIndexPath:indexPath];
    [cell clickToNext];
}

- (TestSelectedQuestionView *)alertView
{
    if (!_alertView) {
        _alertView = [[TestSelectedQuestionView alloc] initWithFrame:self.navigationController.view.bounds];
        WeakSelf(self);
        _alertView.blobk = ^(NSInteger index) {
            if (index == 10000) {
                [weakself goSubmitVC];
            }else{
                
                weakself.currentIndex = index;
                NSIndexPath *indexPath = [NSIndexPath indexPathForItem:weakself.currentIndex inSection:0];
                [weakself.collectionView scrollToItemAtIndexPath:indexPath
                                                atScrollPosition:UICollectionViewScrollPositionCenteredHorizontally
                                                        animated:YES];
                [weakself.collectionView reloadData];
            }
        };
        [self.navigationController.view addSubview:_alertView];
    }
    return _alertView;
}
#pragma mark - IFlyDetectionDelegate
- (void)evaluting:(IFlyDetection *)ifyldetection result:(NSString *)result {
    
    //评测分数
//    CGFloat totalScore = 0;//总分
//    CGFloat standardscore = 0;//
//    CGFloat integrityscore = 0;//完整度分
//    CGFloat fluencyscore = 0;//流畅度分
//    CGFloat accuracyscore = 0;//准确度分
//    
    NSArray<NSString*> *words = [result componentsSeparatedByString:@"\n"];
    
    NSString *searchWord = @"Total Score：";
    NSString *searchWord2 = @"Standard Score：";
    NSString *searchWord3 = @"Integrity Score：";
    NSString *searchWord4 = @"Fluency Score：";
    NSString *searchWord5 = @"Accuracy Acore：";
    for (NSString *obj in words) {
        
        if ([obj containsString:searchWord]) {
            ifyldetection.question.totalScore = [[obj substringFromIndex:searchWord.length] floatValue];
        }
        if ([obj containsString:searchWord2]) {
            ifyldetection.question.standardscore = [[obj substringFromIndex:searchWord2.length] floatValue];
        }
        if ([obj containsString:searchWord3]) {
            ifyldetection.question.integrityscore = [[obj substringFromIndex:searchWord3.length] floatValue];
        }
        if ([obj containsString:searchWord4]) {
            ifyldetection.question.fluencyscore = [[obj substringFromIndex:searchWord4.length] floatValue];
        }
        if ([obj containsString:searchWord5]) {
            ifyldetection.question.accuracyscore = [[obj substringFromIndex:searchWord5.length] floatValue];
        }
        ifyldetection.question.questionRefSorce = ifyldetection.question.totalScore/100.00*ifyldetection.question.score;
      
        DebugLog(@"========= %@ == ",obj);
    }
    
   // DebugLog(@"评测结果: %@ == %f",result,totalScore);
    
    NSFileManager *fm = [NSFileManager defaultManager];
    if ([fm fileExistsAtPath:ifyldetection.question.recordPath]) {
        [HomeRequest upLoadAudioWithPath:ifyldetection.question.recordPath result:^(NSDictionary *url) {
            if (!IsStrEmpty(url[@"fullurl"])) {
                ifyldetection.question.recordUrl = url[@"fullurl"];
            }
        }];
    }
    
}

- (void)onCompleted:(IFlySpeechError *)errorCode
{
    [self clickToNext];
}
- (IFlyDetection *)detection {
    if (!_detection) {
        _detection = [[IFlyDetection alloc] init];
        _detection.delegate = self;
    }
    return _detection;
}
- (void)dealData
{
    
    for (int i=0; i < self.testModel.resource.items.count; i++) {
        
        HSItem *item = self.testModel.resource.items[i];
        HSPart *part = self.testModel.resource_h5.parts[i];
        for (int a=0; a < item.questions.count; a++)
        {
            HSQuestion *quest = item.questions[a];
            HSChild *child = part.children[a];
            if (quest.children.count == 0) {
                HSScore *score = item.scores.firstObject;
                quest.score = score.score;
                quest.answer = child.stem;
            }else{
                [self getQuestionWithQuestion:quest item:item HSChild:child];
            }
        }
       
    }
    
  
  
}
-(void)getQuestionWithQuestion:(HSQuestion *)question item:(HSItem *)item HSChild:(HSChild *)child
{
    for (int i=0; i < question.children.count; i++) {
        HSQuestion *quest = question.children[i];
        HSChild *childN = child.children[i];
        HSScore *score = item.scores[i];
        quest.score = score.score;
        quest.answer = childN.ref_info.solving_idea;
    }
   
}
- (void)dealloc
{
    [PlayManager sharPlayManager].useTime = 0;
   
}
@end
